/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { getIdOfPickedObj } from '@app-base/common/utils/render';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';

enum ElementMode {
  ANGLE = 'angle',
  TOELEMENT = 'toElement',
}

type pickedElementData = pickedVertexData | pickedFaceData;

type FormDataType = {
  curve: pickedLineData;
  axis: pickedLineData;
  mode: string;
  angle: number;
  element?: pickedElementData;
  mode2: string;
  angle2: number;
  element2?: pickedElementData;
};

type Params = {
  curve: string;
  axis: string;
  mode: string;
  angle: number;
  element?: string;
  mode2: string;
  angle2: number;
  element2?: string;
};

function CmdRotateSurface({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    curve: null,
    axis: null,
    mode: 'angle',
    angle: 180,
    element: null,
    mode2: 'angle',
    angle2: 0,
    element2: null,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  const schema: RJSFSchema = useMemo(() => {
    return {
      type: 'object',
      properties: {
        curve: {
          type: 'string',
          format: PickInputRJSFFormat.PickSketchCurve,
        },
        axis: {
          type: 'string',
          format: PickInputRJSFFormat.PickSketchLine,
        },
        mode: {
          type: 'string',
          default: ElementMode.ANGLE,
          title: '第一限制',
          oneOf: [
            {
              title: '角度',
              const: ElementMode.ANGLE,
            },
            {
              title: '直到元素',
              const: ElementMode.TOELEMENT,
            },
          ],
        },
        angle: {
          type: 'number',
          title: formData.mode === ElementMode.ANGLE ? '角度' : '偏移角度',
          format: NumberInputFormat.Angle,
        },
        element:
          formData.mode !== ElementMode.ANGLE
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickVertexAndFace,
              }
            : {},
        mode2: {
          type: 'string',
          default: ElementMode.ANGLE,
          title: '第二限制',
          oneOf: [
            {
              title: '角度',
              const: ElementMode.ANGLE,
            },
            {
              title: '直到元素',
              const: ElementMode.TOELEMENT,
            },
          ],
        },
        angle2: {
          type: 'number',
          title: formData.mode2 === ElementMode.ANGLE ? '角度' : '偏移角度',
          format: NumberInputFormat.Angle,
        },
        element2:
          formData.mode2 !== ElementMode.ANGLE
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickVertexAndFace,
              }
            : {},
      } as RJSFSchema,
    };
  }, [formData]);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const params: Params = props.params;
    const { curve, axis, mode, angle, element, mode2, angle2, element2 } =
      params;

    await initEditDependency([curve, axis, element, element2]);

    setFormData({
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      axis: picker.generatePickObjByPickID(axis) as pickedLineData,
      mode: mode,
      mode2: mode2,
      angle: angle,
      angle2: angle2,
      element: picker.generatePickObjByPickID(element) as pickedElementData,
      element2: picker.generatePickObjByPickID(element2) as pickedElementData,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { curve, axis, mode, mode2, element, element2 } = formData;

    if (mode === ElementMode.TOELEMENT && element == null) {
      return false;
    }

    if (mode2 === ElementMode.TOELEMENT && element2 == null) {
      return false;
    }

    return curve != null && axis != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-rotate-surface', {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const preview = async () => {
    clear();
    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  const execute = async (preview: boolean) => {
    const { curve, mode, mode2, axis, angle, angle2, element, element2 } =
      formData;
    const params = {
      type: 'Revol',
      a: {
        curve: getIdOfPickedObj(curve),
        axis: getIdOfPickedObj(axis),
        mode: mode,
        useDir2: true,
        mode2: mode2,
        angle: angle,
        angle2: angle2,
        element: getIdOfPickedObj(element),
        element2: getIdOfPickedObj(element2),
      },
    };

    await confirmCommand(params, preview);
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      formData={formData}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入轮廓线',
          'ui:options': {
            showArrow: true,
          },
          'ui:autofocus': true,
        },
        axis: {
          'ui:placeholder': '请输入旋转轴',
        },
        angle: {
          'ui:placeholder': '请输入角度1',
        },
        angle2: {
          'ui:placeholder': '请输入角度2',
        },
        element: {
          'ui:placeholder': '请输入限制元素1',
        },
        element2: {
          'ui:placeholder': '请输入限制元素2',
        },
      }}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdRotateSurface: CurvedBaseCommand = {
  id: 'CmdRotateSurface',
  label: 'command.rotate-surface',
  icon: 'commands/curved/revolve-surface',
  help: {
    remark: 'tips.redo',
  },
  create: (label, onClose, props) => (
    <CmdRotateSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
